﻿using Mohe.Scada.Entities.Models;
using Mohe.Scada.Util.Helper;
using NLog;
using Opc.Ua;
using Opc.Ua.Client;
using OpcUaHelper;

namespace Mohe.Scada.WebApi.Services
{
    public class LoadServer
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private OpcUaClient _client;
        private List<LoadInfo> listload = new(10);
        private IFreeSql freeSql;
        public LoadServer(IFreeSql freeSql)
        {
            this.freeSql = freeSql;
            listload = freeSql.Select<LoadInfo>().ToList();
            _client = new OpcUaClient();
            _client.UserIdentity = new UserIdentity("mm", "123456");
            ConnectToServer();

        }

        private void ConnectToServer()
        {
            try
            {
                _client.ConnectServer("opc.tcp://192.168.10.11:4840").GetAwaiter().GetResult();
                _client.AddSubscription("A", "ns=3;s=\"DINT_PC_DB\".\"DINT_TO_PC\"", SubCallback);

            }
            catch (Exception ex)
            {
                logger.Error("连接失败", ex);
            }

        }
        public List<LoadInfo> GetRealTime(int stNo)
        {
            return listload.Where(x => x.BelongsID == stNo).ToList();
        }

        public bool DoCommand(Cmd cmdr)
        {
            try
            {
                if (!_client.Connected)
                {
                    ConnectToServer();
                }
                logger.Info(cmdr.ToJson());
                freeSql.Insert(new CommandRecord("Write Action", "Value:" + cmdr.Val.ToString(), cmdr.Address, DateTime.Now, "11", "False", "True")).ExecuteAffrows();
                _client.WriteNode(cmdr.Address, cmdr.Val);
                Thread.Sleep(50);
                var ret = _client.ReadNode(cmdr.Address);
                return cmdr.Val == (int)ret.Value;
            }
            catch (Exception ex)
            {
                logger.Error("DoCommand", ex);
                logger.Error(ex);

            }
            return false;
        }

        private void SubCallback(string key, MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs args)
        {

            if (key == "A")
            {
                // 如果有多个的订阅值都关联了当前的方法，可以通过key和monitoredItem来区分
                MonitoredItemNotification notification = args.NotificationValue as MonitoredItemNotification;
                if (notification != null)
                {
                    var datav = notification.Value.WrappedValue.ToString().Trim();
                    logger.Info($"SubCallback: {datav}");
                    string[] received_arr = datav.Split('|');
                    received_arr[0] = "0";
                    received_arr[received_arr.Length - 1] = "0";
                    int[] result = Array.ConvertAll(received_arr, int.Parse);

                    //1
                    listload[0].ProductID = result[7920];
                    listload[0].SerialNumber = result[7921];
                    listload[0].PainterID = result[7922];
                    listload[0].Quantity = result[7923];
                    listload[0].AutoProgram = result[7924];
                    listload[0].ExeCarID = result[7925];

                    listload[1].ProductID = result[7926];
                    listload[1].SerialNumber = result[7927];
                    listload[1].PainterID = result[7928];
                    listload[1].Quantity = result[7929];
                    listload[1].AutoProgram = result[7930];
                    listload[1].ExeCarID = result[7931];

                    listload[2].ProductID = result[7932];
                    listload[2].SerialNumber = result[7933];
                    listload[2].PainterID = result[7934];
                    listload[2].Quantity = result[7935];
                    listload[2].AutoProgram = result[7936];
                    listload[2].ExeCarID = result[7937];

                    listload[3].ProductID = result[7938];
                    listload[3].SerialNumber = result[7939];
                    listload[3].PainterID = result[7940];
                    listload[3].Quantity = result[7941];
                    listload[3].AutoProgram = result[7942];
                    listload[3].ExeCarID = result[7943];

                    listload[4].ProductID = result[7944];
                    listload[4].SerialNumber = result[7945];
                    listload[4].PainterID = result[7946];
                    listload[4].Quantity = result[7947];
                    listload[4].AutoProgram = result[7948];
                    listload[4].ExeCarID = result[7949];


                    //2
                    listload[5].ProductID = result[7950];
                    listload[5].SerialNumber = result[7951];
                    listload[5].PainterID = result[7952];
                    listload[5].Quantity = result[7953];
                    listload[5].AutoProgram = result[7954];
                    listload[5].ExeCarID = result[7955];

                    listload[6].ProductID = result[7956];
                    listload[6].SerialNumber = result[7957];
                    listload[6].PainterID = result[7958];
                    listload[6].Quantity = result[7959];
                    listload[6].AutoProgram = result[7960];
                    listload[6].ExeCarID = result[7961];

                    listload[7].ProductID = result[7962];
                    listload[7].SerialNumber = result[7963];
                    listload[7].PainterID = result[7964];
                    listload[7].Quantity = result[7965];
                    listload[7].AutoProgram = result[7966];
                    listload[7].ExeCarID = result[7967];

                    listload[8].ProductID = result[7968];
                    listload[8].SerialNumber = result[7969];
                    listload[8].PainterID = result[7970];
                    listload[8].Quantity = result[7971];
                    listload[8].AutoProgram = result[7972];
                    listload[8].ExeCarID = result[7973];

                    listload[9].ProductID = result[7974];
                    listload[9].SerialNumber = result[7975];
                    listload[9].PainterID = result[7976];
                    listload[9].Quantity = result[7977];
                    listload[9].AutoProgram = result[7978];
                    listload[9].ExeCarID = result[7979];
                }
            }
        }
    }
}
